define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts'], function ($, undefined, Backend, Table, Form, echarts) {

    var Controller = {
        orderCost: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/cost/orderCost' + location.search,
                    add_url: 'scanwork/cost/add',
                    edit_url: 'scanwork/cost/edit',
                    del_url: 'scanwork/cost/del',
                    multi_url: 'scanwork/cost/multi',
                    import_url: 'scanwork/cost/import',
                    table: 'scanwork_order_cost',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function(params) {
                    // 构建筛选条件
                    var filter = {};
                    var orderStatus = $('#order_status').val();
                    var orderNo = $('#order_no').val();
                    var productName = $('#product_name').val();
                    
                    if (orderStatus) filter.order_status = orderStatus;
                    if (orderNo) filter.order_no = orderNo;
                    if (productName) filter.product_name = productName;
                    
                    params.filter = JSON.stringify(filter);
                    return params;
                },
                responseHandler: function(res) {
                    // 更新汇总统计
                    if (res.summary) {
                        $('#total_orders').text(res.summary.total_orders || 0);
                        $('#total_cost').text('¥' + parseFloat(res.summary.total_cost || 0).toFixed(2));
                        $('#avg_profit_rate').text(parseFloat(res.summary.avg_profit_rate || 0).toFixed(1) + '%');
                        $('#total_profit').text('¥' + parseFloat(res.summary.total_profit || 0).toFixed(2));
                    }
                    return res;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'ID', width: 50},
                        {field: 'order_no', title: '订单号', width: 120, searchable: true},
                        {field: 'product_name', title: '产品名称', width: 150, searchable: true},
                        {field: 'quantity', title: '数量', width: 80, formatter: function(v) { return parseInt(v); }},
                        {field: 'material_cost', title: '材料成本', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'labor_cost', title: '人工成本', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'overhead_cost', title: '制造费用', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'total_cost', title: '总成本', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'profit', title: '利润', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'profit_rate', title: '利润率(%)', width: 100, formatter: function(v) { return (v || 0) + '%'; }},
                        {field: 'cost_date', title: '核算日期', width: 100, formatter: function(v) { return v ? new Date(v * 1000).toLocaleDateString() : ''; }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, width: 150}
                    ]
                ]
            });

            // 查询按钮事件
            $(document).on('click', '.btn-search', function() {
                table.bootstrapTable('refresh');
            });

            // 导出按钮事件
            $(document).on('click', '.btn-export', function() {
                var params = {
                    order_status: $('#order_status').val(),
                    order_no: $('#order_no').val(),
                    product_name: $('#product_name').val()
                };
                window.open('scanwork/cost/orderCost/export?' + $.param(params));
            });

            // 绑定事件
            Table.api.bindevent(table);
        },
        
        planCost: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/cost/planCost' + location.search,
                    add_url: 'scanwork/cost/add',
                    edit_url: 'scanwork/cost/edit',
                    del_url: 'scanwork/cost/del',
                    multi_url: 'scanwork/cost/multi',
                    import_url: 'scanwork/cost/import',
                    table: 'scanwork_plan_cost',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function(params) {
                    // 构建筛选条件
                    var filter = {};
                    var planStatus = $('#plan_status').val();
                    var planDate = $('#plan_date').val();
                    
                    if (planStatus) filter.plan_status = planStatus;
                    if (planDate) filter.plan_date = planDate;
                    
                    params.filter = JSON.stringify(filter);
                    return params;
                },
                responseHandler: function(res) {
                    // 更新汇总统计
                    if (res.summary) {
                        $('#total_plans').text(res.summary.total_plans || 0);
                        $('#total_plan_cost').text('¥' + parseFloat(res.summary.total_cost || 0).toFixed(2));
                        $('#executing_plans').text(res.summary.executing_count || 0);
                        $('#completed_plans').text(res.summary.completed_count || 0);
                    }
                    return res;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'ID', width: 50},
                        {field: 'plan_code', title: '计划编号', width: 120, searchable: true},
                        {field: 'plan_name', title: '计划名称', width: 150, searchable: true},
                        {field: 'total_cost', title: '计划成本', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'actual_cost', title: '实际成本', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'cost_variance', title: '差异金额', width: 100, formatter: function(v) { 
                            var amount = parseFloat(v || 0);
                            var color = amount >= 0 ? 'red' : 'green';
                            return '<span style="color:' + color + '">¥' + amount.toFixed(2) + '</span>';
                        }},
                        {field: 'variance_rate', title: '差异率(%)', width: 100, formatter: function(v) { 
                            var rate = parseFloat(v || 0);
                            var color = rate >= 0 ? 'red' : 'green';
                            return '<span style="color:' + color + '">' + rate + '%</span>';
                        }},
                        {field: 'status', title: '状态', width: 80, searchList: {0:'待执行',1:'执行中',2:'已完成'}, formatter: function(v) {
                            var statusMap = {0: '待执行', 1: '执行中', 2: '已完成'};
                            return statusMap[v] || v;
                        }},
                        {field: 'plan_date', title: '计划日期', width: 100, formatter: function(v) { return v ? new Date(v * 1000).toLocaleDateString() : ''; }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, width: 150}
                    ]
                ]
            });

            // 查询按钮事件
            $(document).on('click', '.btn-search', function() {
                console.log('计划成本筛选参数:', {
                    plan_status: $('#plan_status').val(),
                    plan_date: $('#plan_date').val()
                });
                table.bootstrapTable('refresh');
            });

            // 导出按钮事件
            $(document).on('click', '.btn-export', function() {
                var params = {
                    plan_status: $('#plan_status').val(),
                    plan_date: $('#plan_date').val()
                };
                window.open('scanwork/cost/planCost/export?' + $.param(params));
            });

            // 绑定事件
            Table.api.bindevent(table);
        },
        
        variance: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/cost/variance' + location.search,
                    add_url: 'scanwork/cost/add',
                    edit_url: 'scanwork/cost/edit',
                    del_url: 'scanwork/cost/del',
                    multi_url: 'scanwork/cost/multi',
                    import_url: 'scanwork/cost/import',
                    table: 'scanwork_cost_variance',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'variance_amount',
                sortOrder: 'desc',
                responseHandler: function(res) {
                    // 更新汇总统计
                    if (res.summary) {
                        $('#saving_amount').text('¥' + parseFloat(res.summary.saving_amount || 0).toFixed(2));
                        $('#overrun_amount').text('¥' + parseFloat(res.summary.overrun_amount || 0).toFixed(2));
                        $('#net_variance').text('¥' + parseFloat(res.summary.net_variance || 0).toFixed(2));
                    }
                    return res;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'ID', width: 50},
                        {field: 'order_no', title: '订单号', width: 120},
                        {field: 'plan_code', title: '计划编号', width: 120},
                        {field: 'variance_type', title: '差异类型', width: 100, formatter: function(v) {
                            var typeMap = {'material': '材料差异', 'labor': '人工差异', 'overhead': '制造费用差异'};
                            return typeMap[v] || v;
                        }},
                        {field: 'planned_cost', title: '计划金额', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'actual_cost', title: '实际金额', width: 100, formatter: function(v) { return '¥' + parseFloat(v || 0).toFixed(2); }},
                        {field: 'variance_amount', title: '差异金额', width: 100, formatter: function(v) { 
                            var amount = parseFloat(v || 0);
                            var color = amount >= 0 ? 'red' : 'green';
                            return '<span style="color:' + color + '">¥' + amount.toFixed(2) + '</span>';
                        }},
                        {field: 'variance_rate', title: '差异率(%)', width: 100, formatter: function(v) { 
                            var rate = parseFloat(v || 0);
                            var color = rate >= 0 ? 'red' : 'green';
                            return '<span style="color:' + color + '">' + rate + '%</span>';
                        }},
                        {field: 'variance_reason', title: '差异原因', width: 200},
                        {field: 'createtime', title: '创建时间', width: 150, formatter: function(v) { return v ? new Date(v * 1000).toLocaleString() : ''; }},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, width: 150}
                    ]
                ]
            });

            // 查询按钮事件
            $(document).on('click', '.btn-search', function() {
                var params = {
                    variance_type: $('#variance_type').val(),
                    variance_range: $('#variance_range').val()
                };
                table.bootstrapTable('refresh', {query: params});
            });

            // 导出按钮事件
            $(document).on('click', '.btn-export', function() {
                var params = {
                    variance_type: $('#variance_type').val(),
                    variance_range: $('#variance_range').val()
                };
                window.open('scanwork/cost/variance/export?' + $.param(params));
            });

            // 绑定事件
            Table.api.bindevent(table);
        },
        
        analysis: function () {
            // 使用HTML5日期输入
            $('#start_date, #end_date').attr('type', 'date');

            // 查询按钮事件
            $(document).on('click', '.btn-search', function() {
                var startDate = $('#start_date').val();
                var endDate = $('#end_date').val();
                
                if (!startDate || !endDate) {
                    Toastr.error('请选择开始日期和结束日期');
                    return;
                }
                
                loadAnalysisData(startDate, endDate);
            });

            // 导出按钮事件
            $(document).on('click', '.btn-export', function() {
                var startDate = $('#start_date').val();
                var endDate = $('#end_date').val();
                window.open('scanwork/cost/analysis/export?start_date=' + startDate + '&end_date=' + endDate);
            });

            // 加载分析数据
            function loadAnalysisData(startDate, endDate) {
                $.ajax({
                    url: 'scanwork/cost/analysis',
                    type: 'GET',
                    data: {
                        start_date: startDate,
                        end_date: endDate
                    },
                    success: function(response) {
                        if (response.code === 1) {
                            var data = response.data;
                            
                            // 更新汇总数据
                            $('#total_material').text('¥' + parseFloat(data.summary.total_material || 0).toFixed(2));
                            $('#total_labor').text('¥' + parseFloat(data.summary.total_labor || 0).toFixed(2));
                            $('#total_overhead').text('¥' + parseFloat(data.summary.total_overhead || 0).toFixed(2));
                            $('#total_cost').text('¥' + parseFloat(data.summary.total_cost || 0).toFixed(2));
                            
                            // 绘制趋势图
                            drawTrendChart(data.trend);
                        } else {
                            Toastr.error('加载数据失败');
                        }
                    },
                    error: function() {
                        Toastr.error('网络错误');
                    }
                });
            }

            // 绘制趋势图
            function drawTrendChart(trendData) {
                var chartDom = document.getElementById('costTrendChart');
                if (!chartDom) {
                    console.log('图表容器未找到');
                    return;
                }
                
                if (!trendData || trendData.length === 0) {
                    chartDom.innerHTML = '<div class="alert alert-info">暂无数据</div>';
                    return;
                }
                
                // 销毁之前的图表
                if (window.costTrendChart && typeof window.costTrendChart.dispose === 'function') {
                    try {
                        window.costTrendChart.dispose();
                    } catch (e) {
                        console.log('销毁图表时出错:', e);
                    }
                }
                
                // 清空容器
                chartDom.innerHTML = '';
                
                // 初始化图表
                try {
                    window.costTrendChart = echarts.init(chartDom);
                } catch (e) {
                    console.log('初始化图表时出错:', e);
                    return;
                }
                
                var labels = [];
                var costData = [];
                var profitData = [];
                
                trendData.forEach(function(item) {
                    labels.push(item.date);
                    costData.push(parseFloat(item.cost || 0));
                    profitData.push(parseFloat(item.profit || 0));
                });
                
                var option = {
                    title: {
                        text: '成本趋势分析',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            var result = params[0].name + '<br/>';
                            params.forEach(function(item) {
                                result += item.marker + item.seriesName + ': ¥' + item.value.toFixed(2) + '<br/>';
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['成本', '利润'],
                        top: 30
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: labels
                    },
                    yAxis: {
                        type: 'value',
                        axisLabel: {
                            formatter: '¥{value}'
                        }
                    },
                    series: [
                        {
                            name: '成本',
                            type: 'line',
                            data: costData,
                            itemStyle: {
                                color: '#3c8dbc'
                            },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0,
                                    y: 0,
                                    x2: 0,
                                    y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(60, 141, 188, 0.3)'
                                    }, {
                                        offset: 1, color: 'rgba(60, 141, 188, 0.1)'
                                    }]
                                }
                            }
                        },
                        {
                            name: '利润',
                            type: 'line',
                            data: profitData,
                            itemStyle: {
                                color: '#f39c12'
                            },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0,
                                    y: 0,
                                    x2: 0,
                                    y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(243, 156, 18, 0.3)'
                                    }, {
                                        offset: 1, color: 'rgba(243, 156, 18, 0.1)'
                                    }]
                                }
                            }
                        }
                    ]
                };
                
                try {
                    window.costTrendChart.setOption(option);
                } catch (e) {
                    console.log('设置图表选项时出错:', e);
                    return;
                }
                
                // 响应式调整
                window.addEventListener('resize', function() {
                    if (window.costTrendChart && typeof window.costTrendChart.resize === 'function') {
                        try {
                            window.costTrendChart.resize();
                        } catch (e) {
                            console.log('调整图表大小时出错:', e);
                        }
                    }
                });
            }

            // 初始化加载数据
            var startDate = $('#start_date').val();
            var endDate = $('#end_date').val();
            if (startDate && endDate) {
                loadAnalysisData(startDate, endDate);
            }
        },
        
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    
    // 根据当前页面自动调用对应方法
    $(function() {
        var path = window.location.pathname;
        if (path.indexOf('/cost/orderCost') !== -1) {
            Controller.orderCost();
        } else if (path.indexOf('/cost/planCost') !== -1) {
            Controller.planCost();
        } else if (path.indexOf('/cost/variance') !== -1) {
            Controller.variance();
        } else if (path.indexOf('/cost/analysis') !== -1) {
            Controller.analysis();
        }
    });
    
    return Controller;
});
